<template>
    <div class="admin-page">
        <div class="page-header">
            <!-- 添加活动选择器 -->
            <div style="display: flex; align-items: center; margin-bottom: 20px;">
                <span class="search-label">活动选择:</span>
                <el-select v-model="selectedActivity" size="small" style="width: 200px;" @change="handleActivityChange">
                    <el-option label="第一期活动" :value="1"></el-option>
                    <el-option label="第二期活动" :value="2"></el-option>
                </el-select>
            </div>

            <div style="display: flex;justify-content: space-between">
                <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">搜索:</span>
                        <el-input v-model="form.search" size="small" placeholder="id/手机号"
                                  style="width: 160px;"></el-input>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">总金额:</span>
                        <div style="color: red;font-size: 16px">
                            {{ form.total_money }}
                        </div>
                    </div>
                </div>
                <div style="display: flex;  align-items: center; gap: 15px; margin-bottom: 15px;">
                    <el-button type="primary" size="small" @click="toSearch">搜索</el-button>
                    <el-button type="success" size="small" @click="reset">重置</el-button>
                    <el-button type="danger" size="small" @click="sendBonus" v-if="selectedActivity === 1">发放分红</el-button>
                </div>
            </div>

            <el-table :data="selectedActivity === 2 ? tableDataTwo : tableData" height="560" border style="width: 100%;overflow-y: auto"
                      :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small"
                      @selection-change="handleSelectionChange"
                      :row-key="row => row.id">
                <template v-if="selectedActivity === 1">
                  <el-table-column type="selection" width="55" align="center" :selectable="row => row.pidNum >= 5" />
                  <el-table-column prop="paiming" label="排名" align="center" />
                  <el-table-column prop="pid" label="用户id" align="center" />
                  <el-table-column prop="username" label="手机号" align="center" />
                  <el-table-column prop="money" label="分红金额" align="center" />
                  <el-table-column prop="is_send" label="分红状态" align="center">
                    <template slot-scope="scope">
                      <el-tag v-if="scope.row.is_send !== 2"
                              :type="scope.row.is_send === 1 ? 'success' : 'info'">
                        {{ scope.row.is_send === 1 ? '已分红' : '未分红' }}
                      </el-tag>
                      <span v-else></span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="pidNum" label="推荐人数" align="center" />
                </template>
                <template v-else-if="selectedActivity === 2">
                    <el-table-column type="selection" width="55" align="center" :selectable="row => row.pidNum >= 5" />
                  <el-table-column prop="time_rank_desc" label="排名" align="center" width="80" />
                  <el-table-column prop="id" label="用户id" align="center" />
                  <el-table-column prop="username" label="手机号" align="center" />
                  <el-table-column prop="contribution" label="贡献值" align="center" />
                  <el-table-column prop="limit_amount" label="额度" align="center" />
                  <el-table-column label="已发金额" align="center" width="100" :formatter="() => '暂未统计'" />
                  <el-table-column prop="is_send" label="分红状态" align="center">
                    <template slot-scope="scope">
                      <el-tag v-if="scope.row.is_send !== 2"
                              :type="scope.row.is_send === 1 ? 'success' : 'info'">
                        {{ scope.row.is_send === 1 ? '已分红' : '未分红' }}
                      </el-tag>
                      <span v-else>未分红</span>
                    </template>
                  </el-table-column>
                </template>
            </el-table>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            selectedActivity: 1, // 默认选择第一期活动
            form: {
                search: '',
                username: '',
                contribution: '',
                quota: '',
                sent_money: '',
                total_money: '',
                limit_amount: '',
                total_price: ''
            },
            tableData: [],
            tableDataTwo: [],
            statusOptions: [
                { label: '全部', value: '' },
                { label: '已发放', value: 1 },
                { label: '未发放', value: 0 }
            ],
            currentPage: 1,
            pageSize: 15,
            total: 0,
            searchParams: {},
            typeOptions: [],
            mTypeOptions: [],
            selectedRows: [],
        }
    },
    created() {
        this.getTableData()
    },
    methods: {
        // 处理活动切换
        handleActivityChange(type) {
            this.selectedActivity = type;
            this.reset(); // 只重置表单和分页参数，不再重复请求数据
            this.getTableData(); // 只在这里请求一次数据
        },
        handleSelectionChange(val) {
            this.selectedRows = val;
        },
        getTableData(params = {}) {
            // 如果是第二期活动，调用新接口
            if (this.selectedActivity === 2) {
                const requestParams = {
                    page: this.currentPage,
                    pageSize: this.pageSize,
                    type: this.selectedActivity,
                    ...params
                };
                this.$http.get('/admin/Challenge/dataCountTwo', { params: requestParams }).then(result => {
                    if (result.code === 200) {
                        this.tableDataTwo = JSON.parse(JSON.stringify(Array.isArray(result.data) ? result.data : []));
                        console.log('二期tableDataTwo', this.tableDataTwo);
                        this.form.total_money = '暂未统计';
                    } else {
                        this.$message.error(result.msg);
                        this.tableDataTwo = [];
                    }
                }).catch(error => {
                    console.error("获取第二期数据失败:", error);
                    this.$message.error("获取第二期数据失败，请稍后重试");
                    this.tableDataTwo = [];
                    this.total = 0;
                });
                return;
            }

            const requestParams = {
                page: this.currentPage,
                pageSize: this.pageSize,
                type: this.selectedActivity,
                ...params
            };
            this.$http.get('/admin/Challenge/dataCount', { params: requestParams }).then(result => {
                if (result.code === 200) {
                    console.log(result)
                    this.tableData = Array.isArray(result.data.data) ? result.data.data : [];
                    this.form.total_money = result.data.total_money
                    console.log(this.form.total_money)
                    this.total = parseInt(result.data.total) || 0;
                } else {
                    this.$message.error(result.msg);
                    this.tableData = [];
                    this.total = 0;
                }
            }).catch(error => {
                console.error("获取订单列表失败:", error);
                this.$message.error("获取订单列表失败，请稍后重试");
                this.tableData = [];
                this.total = 0;
            });
        },
        // 获取第二期活动的假数据
        getMockData() {
            // 该方法已废弃，无需实现
        },
        toSearch() {
            const formatDate = (date) => {
                if (!date) return '';
                const d = new Date(date);
                const year = d.getFullYear();
                const month = String(d.getMonth() + 1).padStart(2, '0');
                const day = String(d.getDate()).padStart(2, '0');
                const hours = String(d.getHours()).padStart(2, '0');
                const minutes = String(d.getMinutes()).padStart(2, '0');
                const seconds = String(d.getSeconds()).padStart(2, '0');
                const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                const timestamp = new Date(formattedDate).getTime();
                return Math.floor(timestamp / 1000); // 转换为秒级时间戳
            };

            this.searchParams = {
                ...this.form,
                type: this.selectedActivity
            };
            // Remove empty string properties from searchParams before sending
            Object.keys(this.searchParams).forEach(key => {
                if (this.searchParams[key] === '') {
                    delete this.searchParams[key];
                }
            });
            this.currentPage = 1;
            this.getTableData(this.searchParams);
        },
        reset() {
            this.form.search = "";
            this.form.total_money = this.selectedActivity === 2 ? "暂未统计" : "";
            if (this.selectedActivity === 2) {
                this.form.username = "";
                this.form.contribution = "";
                this.form.limit_amount = "";
                this.form.total_price = "";
            } else {
                this.form.username = undefined;
                this.form.contribution = undefined;
                this.form.limit_amount = undefined;
                this.form.total_price = undefined;
            }
            this.searchParams = {};
            this.currentPage = 1;
            // 不再调用getTableData
        },
        async sendBonus() {
            if (!this.selectedRows.length) {
                this.$message.warning('请先选择要分红的用户');
                return;
            }
            this.$confirm('是否确认发放分红？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 只传递所需字段
                const payload = this.selectedRows.map(row => ({
                    username: row.username,
                    pid: row.pid,
                    pidNum: row.pidNum,
                    up_total_money: row.up_total_money,
                    third_earliest_time: row.third_earliest_time,
                    paiming: row.paiming,
                    is_send: 1,
                    money: row.money,
                    total_money: this.form.total_money,
                    type: this.selectedActivity
                }));
                try {
                    const res = await this.$http.post('/admin/Challenge/addRecord', payload);
                    if (res.code === 200) {
                        this.$message.success('发放分红成功');
                        this.getTableData();
                    } else {
                        this.$message.error(res.msg || '发放分红失败');
                    }
                } catch (e) {
                    this.$message.error('发放分红失败，请稍后重试');
                }
            }).catch(() => {});
        },
    }
}
</script>

<style scoped lang="less">
.admin-page {
    padding: 20px;

    .search-label {
        margin-right: 10px;
        color: #606266;
    }

    .el-table {
        margin-top: 20px;
    }

    .el-pagination {
        margin-top: 20px;
        text-align: right;
    }
}
</style>
